package com.project.thisDatabase.elasticsearch.config;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.Objects;

@ConditionalOnProperty(name = "spring.data.elasticsearch.enable", havingValue = "true")
@Configuration
public class ElasticConfig {

    @Value("${spring.data.elasticsearch.cluster.host:}")
    public String host;
    @Value("${spring.data.elasticsearch.cluster.port:}")
    public Integer port;
    @Value("${spring.data.elasticsearch.cluster.scheme:}")
    public String scheme;
    @Value("${spring.data.elasticsearch.cluster.nodes:}")
    public String ipAddress;

    @Bean
    public RestClientBuilder restClientBuilder() {
        if (StringUtils.isNotBlank(host)) {
            return RestClient.builder(makeHttpHost());
        } else if (StringUtils.isNotBlank(ipAddress)) {
            return RestClient.builder(makeHttpHosts());
        }

        return null;
    }

    @Bean
    public RestClient elasticsearchRestClient(){
        RestClientBuilder builder = restClientBuilder();
        if (null != builder) {
            return builder.build();
        }
        return null;
    }

    private HttpHost makeHttpHost() {
        return new HttpHost(host, port, scheme);
    }

    private HttpHost[] makeHttpHosts() {
        String[] ips = ipAddress.split(",");
        return Arrays.stream(ips)
                .map((s)->{
                    String[] address = s.split(":");
                    return new HttpHost(address[0], Integer.parseInt(address[1]), scheme);
                }).filter(Objects::nonNull)
                .toArray(HttpHost[]::new);
    }

    @Bean
    public RestHighLevelClient restHighLevelClient(@Autowired RestClientBuilder restClientBuilder){
        return new RestHighLevelClient(restClientBuilder);
    }
}
